package postpic.domain.session;

import java.text.ParseException;
import java.util.logging.Logger;

import org.json.JSONObject;

import postpic.json.JSONSerializable;

/**
 * Response to pick up by sending a request
 */
public class Response implements JSONSerializable {
	private static final Logger LOGGER = Logger.getLogger(Response.class.getName());
	
	private boolean success = false;

	private JSONObject responseJSON;
	
	private JSONObject json;
	
	public Response() {
		responseJSON = new JSONObject();
		json = new JSONObject();
	}
	
	/**
	 * Constructor for Response.
	 * @param response JSONObject
	 */
	public Response(final JSONObject response) {
		try {
			LOGGER.info(response.toString());
			json = new JSONObject(response.toString());
			success = Boolean.TRUE.equals(response.get("success"));
			response.remove("success");
			this.responseJSON = response;
		} catch (final ParseException ex) {
			LOGGER.warning("Parse Exception" + ex);
		}
	}
	
	/**
	 * Constructor for Response.
	 * @param success boolean
	 * @param response JSONObject
	 */
	public Response(boolean success, JSONObject response) {
		this.success = success;
		this.responseJSON = response;
		
		if (response != null) {
			try {
				json = new JSONObject(response.toString());
				json.put("success", success);
			} catch (final ParseException ex) {
				LOGGER.warning("parse exception" + ex);
			}
		} else {
			json = new JSONObject();
			json.put("success", success);
		}
	}
	
	public void setJSON(final JSONObject json) {
		this.json = json;
		this.json.put("success", this.success);
	}
	
	@Override
	public JSONObject getJSON() {
		return json;
	}
	
	/**
	 * Sets whether or not the request was processed successfully.
	 * @param success
	 */
	public void setSuccessful(final boolean success) {
		this.success = success;
		this.json.put("success", this.success);
	}
	/**
	 * Method successful.
	 * @return boolean */
	public boolean isSuccessful() {
		return success;
	}
	
	/**
	 * Method getResponse.
	 * @return JSONObject */
	public JSONObject getResponse() {
		return responseJSON;
	}
	
	@Override
	public String toString() {
		return getJSON().toString();
	}

	@Override
	public void populateFromJSON(JSONObject json) {
		// TODO write method
		
	}
}
